package com.hwzn.module.admin.service.impl;
import java.util.Date;

import javax.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.hwzn.module.admin.service.AuthService;
import com.hwzn.module.admin.service.UserService;
import com.hwzn.module.core.dos.UserDO;
import com.hwzn.module.core.utils.JwtTokenUtil;
import com.hwzn.module.core.vos.AuthLoginReqVO;
import com.hwzn.module.core.vos.AuthLoginRespVO;
import com.hwzn.module.core.vos.AuthRegisterReqVO;

/**
 * authentication
 *
 * @author jiaobo
 * @date Created in 2024/5/15 14:03
 * @company hw
 **/
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserService userService;

    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(reqVO.getUsername(),reqVO.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        UserDO userDO = (UserDO) authentication.getPrincipal();
        return createToken(userDO.getId());
    }

    @Override
    public void register(AuthRegisterReqVO reqVO) {
        UserDO userDO = new UserDO();
        userDO.setUsername(reqVO.getUsername());
        userDO.setPassword(passwordEncoder.encode(reqVO.getPassword()));
        userDO.setEmail(reqVO.getEmail());
        userDO.setPhone(reqVO.getPhone());
        userDO.setUpdated(new Date());
        userDO.setCreated(new Date());
        userService.addUser(userDO);
    }

    private AuthLoginRespVO createToken(Long id) {
        String token = JwtTokenUtil.createToken(id + "");
        //save redis
        AuthLoginRespVO respVO = new AuthLoginRespVO();
        respVO.setToken(token);
        respVO.setExpiresTime(JwtTokenUtil.EXPIRITION);
        return respVO;
    }
}
